﻿using System;
using System.Net;
using System.Net.Mail;

namespace QuickEmailer
{
    public class EmailNotify
    {
        public string FromAddress { get; set; }
        public string FromName { get; set; }
        public string ToAddress { get; set; }
        public string MessageSubject { get; set; }
        public string MessageBody { get; set; }
        public bool IsHtml { get; set; }
        public bool SmtpAnonymous { get; set; }
        public string SmtpHost { get; set; }
        public string SmtpUser { get; set; }
        public string SmtpPass { get; set; }

        public EmailNotify() {}

        public EmailNotify(string fromAddress, string fromName, string toAddress, string messageSubject,
            string messageBody, bool isHtml, bool smtpAnonymous, string smtpHost, string smtpUser,
            string smtpPass)
        {
            FromAddress = fromAddress;
            FromName = fromName;
            ToAddress = toAddress;
            MessageSubject = messageSubject;
            MessageBody = messageBody;
            IsHtml = isHtml;
            SmtpAnonymous = smtpAnonymous;
            SmtpHost = smtpHost;
            SmtpUser = smtpUser;
            SmtpPass = smtpPass;
        }

        public void SendMessage()
        {
            if ((FromAddress != null) && (ToAddress != null) && (MessageSubject != null) && (MessageBody != null) &&
                (SmtpHost != null))
            {
                SendMessage(FromAddress, FromName, ToAddress, MessageSubject, MessageBody, IsHtml,
                            SmtpHost, SmtpAnonymous, SmtpUser, SmtpPass);
            }
            else
            {
                throw new Exception("Certain fields are required. See the documentation for more info.");
            }
        }

        public void SendMessage(string fromAddr, string fromName, string to, string subject,
            string body, bool isHtml, string smtpHost, bool smtpAnonymous, string smtpUser, string smtpPass)
        {

            MailMessage msg = new MailMessage();
            MailAddress fromAddress = new MailAddress(fromAddr, fromName);
            msg.From = fromAddress;
            msg.To.Add(to);
            msg.Subject = subject;
            msg.Body = body;
            
            if (isHtml) {msg.IsBodyHtml = true;}

            SmtpClient smtp = new SmtpClient();
            smtp.Host = smtpHost;

            NetworkCredential creds = new NetworkCredential();

            if (!SmtpAnonymous)
            {
                creds.UserName = smtpUser;
                creds.Password = smtpPass;
            }
            smtp.Credentials = creds;
            smtp.Send(msg);

        }
    }
}
